package com.onlinefurnitureshop.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.onlinefurnitureshop.management.model.Users;
import com.onlinefurnitureshop.management.service.UsersService;


public class UserRealm extends AuthorizingRealm{
	
	private UsersService usersService;
	
	

	public UsersService getUsersService() {
		return usersService;
	}

	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole(usersService.findRole(username));
        authorizationInfo.setStringPermissions(usersService.findPermissions(username));
        System.out.println("Realm:"+usersService.findRole(username));
        System.out.println("Realm: permission:"+usersService.findPermissions(username).toString());
        return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		System.out.println("Realm:"+username);
		Users user = usersService.findByUsername(username);
		if(user == null)
			throw new UnknownAccountException();
		ByteSource credentialsSalt = ByteSource.Util.bytes("java");
		return new SimpleAuthenticationInfo(
				user.getUsername(),
				user.getPassword(),
				credentialsSalt,
				getName()
		);
	}

}
